import axios from 'axios'
import {  Message } from 'element-ui'
import store from '@/store'
import {removeToken} from "@/utils/auth";
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 60000 // 过期时间
})

service.interceptors.request.use(
    config => {
        // 发送请求之前做的
        const token = !store.getters.token?sessionStorage.getItem('token'):store.getters.token;
        if (token) {
            config.headers['authorization'] = token
        }
        if(/get/i.test(config.method)){
            config.params = config.params || {}
            config.params.temp= Date.parse(new Date()) / 1000
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.status === 401) {
            Message.error('无效的会话，或者登录已过期，请重新登录。');
            removeToken();
            location.href = '/login';
        }else if(res.status === 403){
            Message.error('没有权限访问。');
        }
        if (res.status !== 200  && res.status !== 401) {
            Message({
                message: res.message || 'Error',
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject()
        } else {
            return res.result
        }
    },
    error => {
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
